//! 历史记录

use crate::packet::Packet;
use core::num::Wrapping;
use fixed_queue::History as FixedHistory;

const HISTORY_LEN: usize = 8;

/// 记录
#[derive(PartialEq)]
struct Log {
    id: Wrapping<u8>,
    sn: u8,
    data_sum: Wrapping<u8>,
}
impl Log {
    fn new(packet: &Packet) -> Log {
        let head = &packet.head;
        let data = &packet.data;
        Log {
            id: head.dst.iter().map(|n| Wrapping(*n)).sum(),
            sn: head.sn,
            data_sum: data.iter().map(|n| Wrapping(*n)).sum(),
        }
    }
}

pub struct History {
    inner: FixedHistory<Log, HISTORY_LEN>,
}
impl History {
    pub const fn new() -> History {
        History {
            inner: FixedHistory::new(),
        }
    }
    /// Adds a value to the History.
    ///
    /// If the History did not have an equal element present, `true` is returned.
    ///
    /// If the History did have an equal element present, `false` is returned.
    pub fn insert(&mut self, packet: &Packet) -> bool {
        let new_log = Log::new(packet);
        if self.inner.contains(&new_log) {
            false
        } else {
            self.inner.insert(new_log);
            true
        }
    }
}
